package tlv.bean;

import java.util.List;

public class TlvBean extends TlvBase implements Tlv {
	
	final static int ATTR_START = 16;	//属性开始标识

	public TlvBean() {
	}

	/**
	 * 用于构造TLV包
	 */
	public TlvBean(int type, int serialNo, int reqId, String userIp, int errCode, int attrNum, List<Attr> attr) {
		super();
		build(1, type, serialNo, reqId, userIp, errCode, attrNum, attr);
	}
	
	/**
	 * 用于解析TLV包
	 * @param a
	 */
	public TlvBean(byte[] a){
		build(a, ATTR_START);
	}

	public byte[] toByteArray() {
		int dLen = 16;
		if (!(attr==null&&attr.isEmpty())) {
			for (Attr a : attr) {
				dLen += a.getAttrLen();
			}
		}
		byte[] b = new byte[dLen];
		b[0] = (byte) ver;
		b[1] = (byte) type;
		b[2] = (byte) papChap;
		b[3] = (byte) rsvd;
		b[4] = (byte) (serialNo >> 8 & 0xff);
		b[5] = (byte) (serialNo & 0xff);
		b[6] = (byte) (reqId >> 8 & 0xff);
		b[7] = (byte) (reqId & 0xff);
		byte[] ip = ipv4Address2BinaryArray(userIp);
		System.arraycopy(ip, 0, b, 8, 4);
		b[12] = (byte) (userPort & 0xff);
		b[13] = (byte) (userPort >> 8 & 0xff);
		b[14] = (byte) errCode;
		b[15] = (byte) attrNum;
		// 生成附加属性
		int t1 = 16;
		if (!(attr==null&&attr.isEmpty())) {
			for (Attr a : attr) {
				b[t1] = (byte) a.getAttrType();
				b[t1 + 1] = (byte) a.getAttrLen();
				System.arraycopy(a.getAttrValue(), 0, b, t1 + 2, a.getAttrValue().length);
				t1 += a.getAttrLen();
			}
		}
		return b;
	}
}
